package io.youngledo.usb;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class I18nManager {

    private static I18nManager instance;
    private ResourceBundle bundle;
    private Locale currentLocale;

    private I18nManager() {
        // 根据系统语言自动选择语言
        detectSystemLocale();
        loadBundle();
    }

    public static I18nManager getInstance() {
        if (instance == null) {
            instance = new I18nManager();
        }
        return instance;
    }

    private void detectSystemLocale() {
        Locale systemLocale = Locale.getDefault();
        String language = systemLocale.getLanguage();
        String country = systemLocale.getCountry();

        // 支持中文（简体）和英文
        if ("zh".equals(language)) {
            if ("CN".equals(country) || "TW".equals(country) || "HK".equals(country)) {
                currentLocale = Locale.SIMPLIFIED_CHINESE;
            } else {
                currentLocale = Locale.SIMPLIFIED_CHINESE;
            }
        } else {
            // 默认使用英文
            currentLocale = Locale.ENGLISH;
        }

        log.info("Detected system locale: {}, Using: {}", systemLocale, currentLocale);
    }

    private void loadBundle() {
        try {
            bundle = ResourceBundle.getBundle("messages", currentLocale);
        } catch (Exception e) {
            // 如果加载失败，使用英文作为备选
            System.err.println("Failed to load bundle for locale: " + currentLocale +
                              ", falling back to English");
            bundle = ResourceBundle.getBundle("messages", Locale.ENGLISH);
        }
    }

    public String getString(String key) {
        try {
            return bundle.getString(key);
        } catch (Exception e) {
            System.err.println("Missing translation key: " + key);
            return key; // 返回key作为备选
        }
    }

    public String getString(String key, Object... args) {
        try {
            String pattern = bundle.getString(key);
            return MessageFormat.format(pattern, args);
        } catch (Exception e) {
            System.err.println("Missing translation key: " + key);
            return key; // 返回key作为备选
        }
    }

    public void setLocale(Locale locale) {
        this.currentLocale = locale;
        loadBundle();
    }

    public Locale getCurrentLocale() {
        return currentLocale;
    }

    public boolean isChinese() {
        return currentLocale.getLanguage().equals("zh");
    }

    public boolean isEnglish() {
        return currentLocale.getLanguage().equals("en");
    }
}